package com.joinval.modules.sys.controller;

import com.joinval.common.annotation.SysLog;
import com.joinval.common.utils.Constant;
import com.joinval.common.utils.Result;
import com.joinval.common.validator.AssertUtils;
import com.joinval.modules.sys.entity.SysMenuEntity;
import com.joinval.modules.sys.service.SysMenuService;
import com.joinval.modules.sys.vo.MenuTree;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 菜单
 */
@Api(description = "菜单控制器")
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController extends AbstractController {

	@Autowired
	private SysMenuService sysMenuService;

	/**
	 * 保存
	 */
	@SysLog("保存菜单")
	@ApiOperation(value="保存菜单")
	@PostMapping("/add")
	public Result add(@RequestBody @Valid SysMenuEntity menu){
		checkMenu(menu);
		sysMenuService.save(menu);
		return Result.ok();
	}

	@SysLog("更新菜单")
	@ApiOperation(value="更新菜单")
	@PostMapping("/update")
	public Result update(@RequestBody @Valid SysMenuEntity menu){
		//数据校验
		checkMenu(menu);
		sysMenuService.updateById(menu);
		return Result.ok();
	}

	@ApiOperation(value="菜单查询")
	@GetMapping("/listAsTree")
	public Result listAsTree(){
		List<SysMenuEntity> list = sysMenuService.list();
		List<MenuTree> menuTrees = MenuTree.buildTree(list);
		return Result.ok().data(menuTrees);
	}

	@ApiOperation(value="删除菜单")
	@PostMapping("/delete/{menuId}")
	public Result delete(@PathVariable("menuId") long menuId){
		//判断是否有子菜单或按钮
		List<SysMenuEntity> menuList = sysMenuService.queryListParentId(menuId);
		if(menuList.size() > 0){
			return Result.error("请先删除子菜单");
		}
		sysMenuService.delete(menuId);
		return Result.ok();
	}

	private void checkMenu(SysMenuEntity menu){
		AssertUtils.notEmpty(menu.getName(),"菜单名称不能为空");
		if(menu.getParentId() == null && menu.getMenuId() == null){
			menu.setParentId(Constant.TOP_MENU);
			menu.setType(Constant.MenuType.CATALOG.getValue());
		}else {
			AssertUtils.notNull(menu.getType(),"请选择类型(1：菜单，2：按钮)");
			if(Constant.MenuType.MENU.equals(menu.getType())){
				AssertUtils.notNull(menu.getUrl(),"菜单路径不能为空");
			}else if(Constant.MenuType.BUTTON.equals(menu.getType())){
				AssertUtils.notNull(menu.getPerms(),"按钮权限不能为空");
			}
		}
		AssertUtils.notNull(menu.getOrderNum(),"排序不能为空");
	}
}
